package net.oschina.dajiangnan.wx.process.pay.tools;

import net.oschina.dajiangnan.util.XStreamHelper;
import net.oschina.dajiangnan.wx.util.HttpTookit;
import net.oschina.dajiangnan.wx.util.RandomUtil;
import net.oschina.dajiangnan.wx.util.Signature;
import org.apache.log4j.Logger;

import net.oschina.dajiangnan.wx.constants.Config;
import net.oschina.dajiangnan.wx.process.pay.xmlbean.OrderqueryReq;
import net.oschina.dajiangnan.wx.process.pay.xmlbean.OrderqueryResp;


public class Orderquery {

    private static Logger logger = Logger.getLogger(Orderquery.class);
    
    private static final String url = "https://api.mch.weixin.qq.com/pay/orderquery";
    
    
    public static Result queryByTransactionId(String transaction_id){
        OrderqueryReq orderqueryReq = new OrderqueryReq();
        orderqueryReq.setTransaction_id(transaction_id);
        return query(orderqueryReq);
    }
    
    public static Result queryByOrderid(String orderid){
        OrderqueryReq orderqueryReq = new OrderqueryReq();
        orderqueryReq.setOut_trade_no(orderid);
        return query(orderqueryReq);
    }
    
    
    
    
    
    
    
    
    
    private static Result query(OrderqueryReq orderqueryReq){
        orderqueryReq.setAppid(Config.appid);
        orderqueryReq.setMch_id(Config.mch_id);
        orderqueryReq.setNonce_str(RandomUtil.getRandomStr(32));
        try {
            orderqueryReq.setSign(Signature.getSign(orderqueryReq, null, Config.apikey));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        
        logger.debug("发送的订单查询请求参数如下\r\n" + orderqueryReq);
        String xmlStr = new HttpTookit().doPost(url,orderqueryReq.toString(),null,null,"UTF-8");
        OrderqueryResp orderqueryResp = XStreamHelper.toBean(xmlStr, OrderqueryResp.class);
        logger.debug("接收订单查询应答内容如下\r\n" + orderqueryResp);
        

        if(!orderqueryResp.islegalSign(Config.apikey)){
            Result result = new Result();
            result.setMsg("OrderqueryResp UnlegalSign");
            return result;
        }
        
        if(orderqueryResp.getReturn_code().equals("SUCCESS")){
            Result result = new Result();
            result.setOrderqueryResp(orderqueryResp);
            return result;
        }else{
            return null;
        }
    }
    
    
    public static class Result{
        private String msg;
        private OrderqueryResp orderqueryResp;
        
        public String getMsg() {
        
            return msg;
        }
        
        public void setMsg(String msg) {
        
            this.msg = msg;
        }
        
        public OrderqueryResp getOrderqueryResp() {
        
            return orderqueryResp;
        }
        
        public void setOrderqueryResp(OrderqueryResp orderqueryResp) {
        
            this.orderqueryResp = orderqueryResp;
        }
        
    }
    
}
